<template>
  <div class="container">
    <el-dialog title="编辑商超退货单" width="90%" :visible.sync="editDialog.centerDialogVisible" @open="getData" @close="cancel"
      center>
      <el-table :data="tableData" border style="width: 100%" empty-text="暂无数据">
        <el-table-column prop="goods_name" label="商品名称" align="center"></el-table-column>
        <el-table-column prop="erp_goods_code" label="商品编码" align="center"></el-table-column>
        <el-table-column prop="bar_code" label="条码" align="center"></el-table-column>
        <el-table-column prop="box_qty" label="箱数" align="center"></el-table-column>
        <el-table-column prop="category_name" label="分类名称" align="center"></el-table-column>
        <el-table-column prop="category_code" label="分类编码" align="center"></el-table-column>
        <el-table-column prop="goods_spec" label="规格" align="center"></el-table-column>
        <el-table-column prop="goods_unit" label="单位" align="center"></el-table-column>
        <el-table-column prop="refund_code" label="erp退货编码" align="center"></el-table-column>
        <el-table-column label="供应商" width="250px" align="center">
          <template slot-scope="scope">
            <el-select size="small" v-model="scope.row.supplier_name" :multiple="false" filterable remote center
              reserve-keyword placeholder="请选择供应商" :remote-method="insideRemoteMethod" :loading="inside.loading"
              @change="getOptionId(scope)">
              <el-option v-for="item in inside.options" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="采购员" width="250px" align="center">
          <template slot-scope="scope">
            <el-select size="small" v-model="scope.row.buyer_name" :multiple="false" filterable remote center
              reserve-keyword placeholder="请选择采购员" :remote-method="insidePurchaseMethod" :loading="purchase.loading"
              @change="getPurchases(scope)">
              <el-option v-for="item in purchase.option" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="退货数量" width="150px" align="center">
          <template slot-scope="scope">
            <el-input-number size="small" :controls="false" @change="modification(scope)"
              v-model="scope.row.refund_num"></el-input-number>
          </template>
        </el-table-column>
        <el-table-column label="生产日期" width="600px" align="center">
          <template slot-scope="scope">
            <div class="timeItem" v-for="item in scope.row.produce_date_shelf_life">
              <div v-if="item.produce_date" class="time">{{ item.produce_date+"【"+(item.due_date?item.due_date:'无')+"/"+item.shelf_life+"天】"}}</div>
              <div v-else class="time">无生产日期</div>
              <el-input-number size="small" :controls="false" v-model="item.batch_num"
                :max="scope.row.bool ? Infinity : item.max_batch_num"></el-input-number>
              <div v-if="!scope.row.bool" class="timeMax">最大值：{{ item.max_batch_num }}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="refund_price" label="退货价格" align="center"></el-table-column>
        <el-table-column label="加价" width="150px" align="center">
          <template slot-scope="scope">
            <el-input-number size="small" :controls="false" v-model="scope.row.markup"
              @change='markup(scope)'></el-input-number>
          </template>
        </el-table-column>
        <el-table-column prop="sourceprice" label="入库价格" align="center"></el-table-column>

        <el-table-column prop="rk_spec" label="入库箱规" align="center"></el-table-column>
        <el-table-column label="入库类型" width="150px" align="center">
          <template slot-scope="scope">
            <el-select v-model="scope.row.is_save_stock" placeholder="请选择入库类型">
              <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
              </el-option>
            </el-select>
          </template>
        </el-table-column>
        <el-table-column prop="package.name" label="包装箱" align="center"></el-table-column>
        <el-table-column prop="packagingboxspec" label="包装箱规格" align="center"></el-table-column>
        <el-table-column label="备注" align="center" width="250px">
          <template slot-scope="scope">
            <el-input type="textarea" :rows="2" placeholder="请输入内容" v-model="scope.row.notes">
            </el-input>
          </template>
        </el-table-column>
      </el-table>
      <!-- <div class="pagination">
        <el-pagination
          @size-change="handleCurrentChange"
          @current-change="handleSizeChange"
          :current-page.sync="pageData.page"
          :page-sizes="pageData.pageSizes"
          :page-size="pageData.pageSize"
          :layout="pageData.layout"
          :total="pageData.total"
        ></el-pagination>
      </div>-->

      <div slot="footer" class="dialog-footer">
        <el-button @click="cancel">取 消</el-button>
        <el-button type="primary" @click="confirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  findRefundOrderInfo,
  editRefundData,
} from "@/api/salesReturn/salesReturnList";
import { selectSupplierList } from "@/api/putStorage/superPurchaseList";
import { selectSupplierData } from "@/api/supplier/supplierList"; //供应商
import { getList } from "@/api/putStorage/putStotageList"; //采购员
export default {
  props: {
    editDialog: Object,
  },
  data() {
    return {
      tableData: [],
      options: [
        {
          value: 1,
          label: "入库",
        },
        {
          value: 0,
          label: "不入库",
        },
      ],
      purchase: {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      },
      inside: {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      },
      // pageData: {
      //   pageSizes: [10, 20],
      //   pageSize: 10,
      //   page: 1,
      //   total: null,
      //   layout: "total, sizes, prev, pager, next, jumper"
      // }
    };
  },
  methods: {
    cancel() {
      this.tableData = [];
      this.inside = {
        innerVisible: false,
        options: [],
        value: "",
        list: [],
        loading: false,
      };
      this.purchase = {
        innerVisible: false,
        option: [],
        value: "",
        list: [],
        loading: false,
      };
      this.editDialog.centerDialogVisible = false;
    },
    confirm() {
      let arr = [];
      let bool = true;
      this.tableData.forEach((res) => {
        let batch_num = 0;
        if (res.produce_date_shelf_life != null) {
          res.produce_date_shelf_life.forEach((item) => {
            batch_num += item.batch_num;
          });
          if (res.refund_num != batch_num) {
            bool = false;
            this.$message({
              duration: "4000",
              type: "info",
              message: "生产日期退货数量与实际退货数量不相符",
            });
          } else {
            arr.push({
              id: res.id,
              refund_num: res.refund_num,
              refund_price: res.refund_price,
              rk_spec: res.rk_spec,
              supplier_id: res.supplier_id,
              supplier_code: res.supplier_code,
              supplier_name: res.supplier_name,
              markup: res.markup,
              is_save_stock: res.is_save_stock,
              produce_date_shelf_life: res.produce_date_shelf_life,
              buyer_id: res.buyer_id,
              buyer_code: res.buyer_code,
              buyer_name: res.buyer_name,
              notes: res.notes
            });
          }
        } else {
          arr.push({
            id: res.id,
            refund_num: res.refund_num,
            refund_price: res.refund_price,
            rk_spec: res.rk_spec,
            supplier_id: res.supplier_id,
            supplier_code: res.supplier_code,
            supplier_name: res.supplier_name,
            markup: res.markup,
            is_save_stock: res.is_save_stock,
            produce_date_shelf_life: res.produce_date_shelf_life,
            buyer_id: res.buyer_id,
            buyer_code: res.buyer_code,
            buyer_name: res.buyer_name,
            notes: res.notes
          });
        }
      });
      if (bool) {
        let data = {
          id: this.editDialog.id,
          goods: JSON.stringify(arr),
        };
        editRefundData(data).then((res) => {
          if (res.code == 0) {
            this.$message({
              type: "success",
              message: res.msg || res.message,
            });
            this.cancel();
          } else {
            this.$message({
              type: "error",
              message: res.msg || res.message,
            });
          }
        });
      }
    },
    // 嵌套搜索供应商数据
    insideRemoteMethod(query) {
      if (query !== "") {
        this.getSupplierList(query);
      } else {
        this.inside.options = [];
      }
    },
    //获取供应商数据
    getSupplierList(query) {
      let data = {
        name: query,
        page: 1,
        limit: 100,
      };
      this.inside.loading = true;
      selectSupplierData(data).then((res) => {
        this.inside.options = res.data.paginate.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}(${item.supplier_code})`,
            code: `${item.supplier_code}`,
          };
        });
        this.inside.loading = false;
      });

      // selectSupplierList(data).then((res) => {
      //   this.inside.list = res.data.paginate.data.map((item) => {
      //     return {
      //       value: `${item.id}`,
      //       label: `${item.supplier_name}`,
      //       code: `${item.supplier_code}`,
      //     };
      //   });
      //   this.inside.loading = false;
      //   this.inside.options = this.inside.list.filter((item) => {
      //     console.log(item.label.toLowerCase(), query.toLowerCase(), 3333);
      //     return (
      //       item.label.toLowerCase().indexOf(query.toLowerCase()) > -1 ||
      //       item.code.toLowerCase().indexOf(query.toLowerCase()) > -1
      //     );
      //   });
      // });
    },
    insidePurchaseMethod(query) {
      if (query !== "") {
        this.getPurchase(query);
      } else {
        this.purchase.option = [];
      }
    },
    getPurchases(e) {
      let data = this.purchase.option.filter((res) => {
        return res.value == e.row.buyer_name;
      });
      e.row.buyer_code = data[0].value;
      e.row.buyer_id = data[0].id;
      e.row.buyer_name = data[0].name;
      this.$set(this.tableData, e.$index, e.row);
    },
    getPurchase(key = "") {
      let data = {
        page: 1,
        limit: 100,
        key,
      };
      //获取商超采购员列表
      getList(data).then((res) => {
        this.purchase.option = res.data.map((item) => {
          return {
            value: item.code,
            label: item.name,
            id: item.id,
            name: item.name,
          };
        });
      });
    },
    getData() {
      let data = {
        // limit: this.pageData.pageSize,
        // page: this.pageData.page,
        id: this.editDialog.id,
      };

      findRefundOrderInfo(data).then((res) => {
        if (res.code == 0) {
          res.data.info.refund_goods.forEach((item) => {
            item.bool =
              parseFloat(item.refund_num) > parseFloat(item.old_refund_num)
                ? true
                : false;
            item.sourceprice = (item.refund_price - item.markup).toFixed(4);
          });
          this.tableData = res.data.info.refund_goods;
          // this.pageData.page = res.data.current_page;
          //   this.pageData.pagesize = res.data.per_page;
          //   this.pageData.total = res.data.total;
        }
      });
      this.getDatas();
      this.getPurchase();
    },
    markup(scope) {
      scope.row.sourceprice = (
        scope.row.refund_price - scope.row.markup
      ).toFixed(4);
      this.$set(this.tableData, scope.$index, scope.row);
    },
    getDatas() {
      let data = {
        page: 1,
        limit: 100,
      };
      //获取供应商列表
      selectSupplierData(data).then((res) => {
        this.inside.options = res.data.paginate.data.map((item) => {
          return {
            value: `${item.id}`,
            label: `${item.supplier_name}(${item.supplier_code})`,
            code: `${item.supplier_code}`,
          };
        });
      });
    },
    //修改退货数量或者入库规格
    modification(scope) {
      scope.row.box_qty = (scope.row.refund_num / scope.row.rk_spec).toFixed(4);
      scope.row.bool =
        parseFloat(scope.row.refund_num) > parseFloat(scope.row.old_refund_num)
          ? true
          : false;
      if (!scope.row.bool) {
        if (this.tableData[scope.$index].produce_date_shelf_life != null) {
          this.tableData[scope.$index].produce_date_shelf_life.forEach(
            (res) => {
              res.batch_num =
                res.batch_num > res.max_batch_num
                  ? res.max_batch_num
                  : res.batch_num;
            }
          );
        }
      }
      this.$set(this.tableData, scope.$index, scope.row);
    },
    getOptionId(e) {
      let arr = this.inside.options.filter((res) => {
        return res.value == e.row.supplier_name;
      });
      e.row.supplier_code = arr[0].code;
      e.row.supplier_id = arr[0].value;
      e.row.supplier_name = arr[0].label;
      this.$set(this.tableData, e.$index, e.row);
    },
    //每页多少条
    handleCurrentChange(val) {
      this.pageData.page = 1;
      this.pageData.pageSize = val;
      this.getData();
    },
    //选取页数
    handleSizeChange(page) {
      this.pageData.page = page;
      this.getData();
    },
  },
};
</script>
<style scoped>
.pagination {
  text-align: right;
  padding: 10px;
}

.timeItem {
  display: flex;
  justify-content: space-around;
  margin-bottom: 3px;
}

.timeItem .time {
  line-height: 32px;
  width: 300px;
}

.timeMax {
  line-height: 32px;
  color: red;
  width: 100px;
}
</style>